﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using XihSolutions.DotMSN;
using Wiyan.Code.PowerMSNRobotLibrary.SDK;
using System.Threading;

namespace Wiyan.Code.PowerMSNRobotLibrary.Manager
{
    /// <summary>
    /// Summary description for ConversationForm.
    /// </summary>
    public class ConversationProxy
    {       
        /// <summary>
        /// </summary>
        private Conversation _conversation;

        /// <summary>
        /// The conversation object which is associated with the form.
        /// </summary>
        public Conversation Conversation
        {
            get { return _conversation; }
        }

        public ConversationProxy(Conversation conversation)
        {
            _conversation = conversation;

            Conversation.Switchboard.TextMessageReceived += new TextMessageReceivedEventHandler(Switchboard_TextMessageReceived);
            Conversation.Switchboard.SessionClosed += new SBChangedEventHandler(Switchboard_SessionClosed);
            Conversation.Switchboard.ContactJoined += new ContactChangedEventHandler(Switchboard_ContactJoined);
            Conversation.Switchboard.ContactLeft += new ContactChangedEventHandler(Switchboard_ContactLeft);
        }

        private void SendInput(string messageBody)
        {
            // check whether there is input
            if (messageBody.Length == 0) return;

            // if there is no switchboard available, request a new switchboard session
            if (Conversation.SwitchboardProcessor.Connected == false)
            {
                Conversation.Messenger.Nameserver.RequestSwitchboard(Conversation.Switchboard, this);
            }

            // note: you can add some code here to catch the event where the remote contact lefts due to being idle too long
            // in that case Conversation.Switchboard.Contacts.Count equals 0.            

            TextMessage message = new TextMessage(messageBody);

            /* You can optionally change the message's font, charset, color here.
             * For example:
             * message.Color = Color.Red;
             * message.Decorations = TextDecorations.Bold;
             */

            Conversation.Switchboard.SendTextMessage(message);

            // History
            // TODO
        }

        private delegate void PrintTextDelegate(string name, string text);

        private void MessageDelaySender(object sender, string message)
        {
            if (string.IsNullOrEmpty(message) == false)
            {
                SendInput(message);
            }
        }

        private void Switchboard_TextMessageReceived(object sender, TextMessageEventArgs e)
        {
            // History

            // Filter
            RobotManager manager = RobotManager.GetInstance();
            bool isApproved = manager.IsApproved(e.Sender.Mail);

            if (isApproved == true)
            {
                manager.MessageASyncSender = this.MessageDelaySender;

                // Send typing message
                Conversation.Switchboard.SendTypingMessage();

                Thread.Sleep(200);

                string replyMessage = null;
                bool shouldReply = false;

                if (manager.CurrentContact != null && manager.CurrentContact.Mail != e.Sender.Mail)
                {
                    shouldReply = true;
                    replyMessage = string.Format("System is controled by {0}", manager.CurrentContact.Mail);
                }
                else
                {
                    if (manager.CurrentContact == null)
                        manager.CurrentContact = e.Sender;

                    shouldReply = manager.ApplyFilter(e.Sender.Name.GetHashCode(), e.Message.Text, ref replyMessage);
                }

                // Send reply if needed
                if (shouldReply)
                {
                    SendInput(replyMessage);
                }
                else
                {
                    SendInput("Echo: " + e.Message.Text);
                }
            }
            else
            {
                Trace.WriteLine(string.Format("New text message is recieved from no approved user. Sender:{0} Message body:{1}", e.Sender.Mail, e.Message.Text));
            }
        }

        private void Switchboard_SessionClosed(object sender, EventArgs e)
        {
        }

        private void Switchboard_ContactJoined(object sender, ContactEventArgs e)
        {
        }

        private void Switchboard_ContactLeft(object sender, ContactEventArgs e)
        {
        }
    }
}
